package com.bristua.barcode.job;

import com.bristua.barcode.common.exception.SystemException;
import com.bristua.barcode.common.util.JsonUtil;
import com.bristua.barcode.supplier.model.TChannelRequestConfig;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;


public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String httpGet(String url) {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
		method.getParams().setContentCharset("UTF-8");
//		method.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,image/wxpic,image/sharpp,image/apng,image/tpg,*/*;q=0.8");
		method.setRequestHeader("Accept-Encoding","gzip, deflate, br");
		method.setRequestHeader("Accept-Language","zh-CN,en-US;q=0.9");
		method.setRequestHeader("User-Agent","Mozilla/5.0 (Linux; Android 6.0.1; vivo X9 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044704 Mobile Safari/537.36 MMWEBID/8592 MicroMessenger/7.0.3.1400(0x2700033C) Process/tools NetType/WIFI Language/zh_CN");
		method.setRequestHeader("Upgrade-Insecure-Requests","1");
        method.setRequestHeader("Connection","keep-alive");
        method.setRequestHeader("Host","ipos.lakala.com");
        method.setRequestHeader("accept", "application/xml");
        String result = null;

        try {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                result = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"), "UTF-8");
            } else {
                logger.info("Method failed: " + method.getStatusLine());
            }
//
//            InputStream is = method.getResponseBodyAsStream();
//            GZIPInputStream gis = new GZIPInputStream(is);
//            BufferedReader br = new BufferedReader(new InputStreamReader(gis,"UTF-8"));
//            String line = "";
//            while((line=br.readLine())!=null) {
//                System.out.println(line);
//            }

            Header[] responseHeaders = method.getResponseHeaders();
            if(responseHeaders!=null && responseHeaders.length>0){
                for(Header header : responseHeaders){
                    HeaderElement[] elements = header.getElements();
                    if(elements!=null && elements.length>0){
                        for(HeaderElement headerElement : elements){
                            System.out.println(headerElement.getName()+":"+headerElement.getValue());

                        }
                    }
                }
            }
        } catch (HttpException e) {
            logger.info("Please check your provided http address!{}");
            throw new SystemException(e);
        } catch (IOException e) {
//            e.printStackTrace();
            if (method != null)
                method.releaseConnection();
            method = null;
            client = null;
            throw new SystemException(e);
        }
        return result;
    }


    public static String postJSON(String strUrl, String param,String cookies) {
//			String params=JSONObject.fromObject(param).toString();
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection","keep-alive");
            connection.setRequestProperty("Host","s.lakala.com");
            connection.setRequestProperty("Upgrade-Insecure-Requests","1");
            connection.setRequestProperty("Accept", "application/json, text/plain, */*");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("Referer","https://s.lakala.com/");
            connection.setRequestProperty("Origin","https://s.lakala.com");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            connection.setRequestProperty("Cookie", "NTKF_T2D_CLIENTID=guest1CD1BE65-15AF-0754-69A5-F41ACB7F8A2D; " +
                    "UM_distinctid=16af41b50e0156-03a9eac6acf7ce-651a107e-1fa400-16af41b50e16ba; Hm_lvt_c968abbd69153a3bb1e5d27388c957df=1558873558,1558873622;" +
                    " aliyungf_tc=AQAAAFGhEx3IQwoA8ZHpd+XihaQ6yuGX;" +
                    " route=173deaae32fb41d3892e8298e8fa67bd; " +
                    "permissions=%5B%22sys%3Aother%3Aproblem%22%2C%22sys%3Areal%3Atransaction%3Asearch%22%2C%22sys%3Amerchant%3Adetail%22%2C%22sys%3Asettlement%3Atransaction%3AgroupPeriod%22%2C%22sys");
            if(!StringUtils.isEmpty(cookies)){
                connection.setRequestProperty("Cookie",cookies);
            }

            if (param != null ) {
                byte[] writebytes = param.getBytes();
                // 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
//
//
//            int length = (int) connection.getContentLength();
//            InputStream is = connection.getInputStream();
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8");
//                return result;
//            }
        } catch (IOException e) {
            throw new SystemException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String postJSON(String strUrl, String param) {
//			String params=JSONObject.fromObject(param).toString();
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(50000);
            connection.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 6.0.1; vivo X9 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044704 Mobile Safari/537.36 MMWEBID/8592 MicroMessenger/7.0.3.1400(0x2700033C) Process/tools NetType/WIFI Language/zh_CN");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            connection.setRequestProperty("Referer","https://ipos.lakala.com/q/pay/wcpay?code=061wSjif2Y2nzH0wNehf2CDcif2wSji8&state=23A876FAD57742539905D4D9732A2DA0");
            connection.setRequestProperty("Origin","https://ipos.lakala.com");
            connection.setRequestProperty("Connection","keep-alive");
            connection.setRequestProperty("Host","ipos.lakala.com");


            if (param != null ) {
                byte[] writebytes = param.getBytes();
                // 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
//
//
//            int length = (int) connection.getContentLength();
//            InputStream is = connection.getInputStream();
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8");
//                return result;
//            }
        } catch (IOException e) {
            throw new SystemException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }



    public static String postForm(String strUrl, String param) {
//			String params=JSONObject.fromObject(param).toString();
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(50000);
            connection.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            connection.setRequestProperty("Referer","https://b.jlpay.com/personallogin/logout");
            connection.setRequestProperty("Origin","https://b.jlpay.com");
            connection.setRequestProperty("Connection","keep-alive");
            connection.setRequestProperty("Host","b.jlpay.com");

            connection.setRequestProperty("Cookie", "Hm_lvt_12519643a012372b092ec624530c8d8b=1567652707,1568036002,1568084178,1568185335; JSESSIONID=FB96DCC59F9EE507410A5C6F117B74E42; mt_merchant_session_id=FB96DCC59F9EE507410A5C6F117B74E4; Hm_lpvt_12519643a012372b092ec624530c8d8b=1568186841" );

            if (param != null ) {
                byte[] writebytes = param.getBytes();
                // 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
//
//
//            int length = (int) connection.getContentLength();
//            InputStream is = connection.getInputStream();
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8");
//                return result;
//            }
        } catch (IOException e) {
            throw new SystemException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    public static String   httpRequest(String strUrl, String param, String cookie,TChannelRequestConfig tChannelRequestConfig) {
//			String params=JSONObject.fromObject(param).toString();
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(tChannelRequestConfig.getRequestMethod());
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(50000);
            connection.setRequestProperty("Accept",tChannelRequestConfig.getAccept());
            connection.setRequestProperty("Accept-Encoding",tChannelRequestConfig.getAcceptEncoding());
            connection.setRequestProperty("Accept-Language",tChannelRequestConfig.getAcceptLanguage());
            connection.setRequestProperty("User-Agent",tChannelRequestConfig.getUserAgent());
            connection.setRequestProperty("X-Requested-With",tChannelRequestConfig.getxRequestedWith());
            connection.setRequestProperty("Content-Type",tChannelRequestConfig.getContentType());
            connection.setRequestProperty("Referer",tChannelRequestConfig.getReferer());
            connection.setRequestProperty("Origin",tChannelRequestConfig.getOrigin());
            connection.setRequestProperty("Connection",tChannelRequestConfig.getConnection());
            connection.setRequestProperty("Host",tChannelRequestConfig.getHost());

            connection.setRequestProperty("Cookie", cookie);

            if (param != null ) {
                byte[] writebytes = param.getBytes();
                // 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
//
//
//            int length = (int) connection.getContentLength();
//            InputStream is = connection.getInputStream();
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8");
//                return result;
//            }
        } catch (IOException e) {
            throw new SystemException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @SuppressWarnings("rawtypes")
    protected static String httpPost(String url, Map<String, Object> paramMap) {
        String content = null;
        if (url == null || url.trim().length() == 0)
            return null;
        HttpClient httpClient = new HttpClient();

        httpClient.getParams().setContentCharset("UTF-8");
        httpClient.getParams().setParameter("Accept","application/json, text/javascript, */*; q=0.01");
        httpClient.getParams().setParameter("Accept-Encoding","gzip, deflate, br");
        httpClient.getParams().setParameter("User-Agent","Mozilla/5.0 (Linux; Android 6.0.1; vivo X9 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044704 Mobile Safari/537.36 MMWEBID/8592 MicroMessenger/7.0.3.1400(0x2700033C) Process/tools NetType/WIFI Language/zh_CN");
        httpClient.getParams().setParameter("X-Requested-With","XMLHttpRequest");
        httpClient.getParams().setParameter("Content-Length",String.valueOf(JsonUtil.toJson(paramMap).getBytes().length));
        httpClient.getParams().setParameter("Content-Type","application/json; charset=UTF-8");
        httpClient.getParams().setParameter("Referer","https://ipos.lakala.com/q/pay/wcpay?code=061wSjif2Y2nzH0wNehf2CDcif2wSji8&state=2922AB7C188E402A9C6684E450725852");
        httpClient.getParams().setParameter("Origin","https://ipos.lakala.com");
        httpClient.getParams().setParameter("Connection","keep-alive");
        httpClient.getParams().setParameter("Host","ipos.lakala.com");
//        connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
//        httpClient
//                .getParams()
//                .setParameter(
//                        HttpMethodParams.USER_AGENT,
//                        "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");

        // httpClient.getHostConfiguration().setProxy("128.128.176.74", 808);

        PostMethod method = new PostMethod(url);
        if (paramMap != null) {
            Iterator it = paramMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next() + "";
                Object o = paramMap.get(key);
                if (o != null && o instanceof String) {
                    method.addParameter(new NameValuePair(key, o.toString()));
                }
                if (o != null && o instanceof String[]) {
                    String[] s = (String[]) o;
                    if (s != null)
                        for (int i = 0; i < s.length; i++) {
                            method.addParameter(new NameValuePair(key, s[i]));
                        }
                }
            }
        }

        try {
            logger.info("method.getPath=" + method.getQueryString());
            logger.info("getURI=" + method.getURI());
            httpClient.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                content = method.getResponseBodyAsString();
            } else {
                logger.info("Method failed: " + method.getStatusLine());
            }
        } catch (HttpException e1) {
            throw new SystemException(e1);
        } catch (IOException e1) {
            throw new SystemException(e1);
        } finally {
            if (method != null)
                method.releaseConnection();
            method = null;
            httpClient = null;
        }
        return content;
    }


    @SuppressWarnings("rawtypes")
    public static String urlParamPac(String url, Map<String, Object> paramMap) {
        StringBuilder stringBuilder = new StringBuilder(url + "?");
        Iterator it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next() + "";
            Object value = paramMap.get(key);
            stringBuilder.append(key + "=" + value + "&");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    @SuppressWarnings("rawtypes")
    protected static String urlParamSet(String url, Map<String, Object> paramMap) {
        StringBuilder stringBuilder = new StringBuilder(url);
        Iterator it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next() + "";
            Object value = paramMap.get(key);
            stringBuilder.append(key + "=" + value + "&");
        }

        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    public static void main(String[] args) throws Exception {
//        HttpClientUtils.httpGet("https://ipos.lakala.com/q/pay/wcpay?code=081poFFE0NWElk2nh9FE0GxHFE0poFFK&state=0B0F22D0E8C04B40AC8B07DD8B52B4E5");
//        Map map = new HashMap();
//        map.put("a","asdfsdf");
//        String s = JsonUtil.toJson(map);
//        System.out.println(s);
        while (true){
            Thread.sleep(10000);
                    String a =  postForm("https://b.jlpay.com/trade.mt","tradeTimeStart=2019-08-31+23%3A00%3A00&tradeTimeEnd=2019-09-01+23%3A00%3A00");
            System.out.println(a);
        }
//        postJSON("http://localhost:8877/customer/add/123123/123123",null);



//
// String a = "appid=wxd23604aba7ed0487&redirect_uri=https%3A%2F%2Fipos.lakala.com%2Fq%2Fpay%2Fwcpay&response_type=code&scope=snsapi_base&state=7F0F75411EDD4870BAD87A9DEACD44B4&connect_redirect=1";
//        String[] split = a.split("&");
//        for(String str : split){
//            String[] split1 = str.split("=");
//            if("state".equals(split1[0])){
//                System.out.println(split1[1]);
//            }
//        }
/*//		String URL = "http://116.204.64.165:7880/IWMS/PayNotify/ccbpayCallBack";
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("success", true);
//		map.put("code", "123");
//		System.out.println(HttpClientUtils.httpPost(URL, map));
		
		String Url="http://119.79.224.116:20014/JLESServer/POST_SCM_DJ?Type=Post_EsOrder&USERNAME=JLSOFT&PASSWORD=88888&SIGNXML={\"Parms\":\"JSONXML\",\"Sign\":\"4d4d7828d59fd5f797ea7bccae99c9ec\"}&JSONXML={\"OrderId\":\"201312050001\",\"created\":\"2013-11-11\",\"modified\":\"2013-11-11\",\"Pay_time\":\"2013-11-11\",\"end_time\":\"2013-11-11\",\"Status\":\"绛夊緟鍗栧鍙戣揣\",\"shipping_type\":\"express\",\"title\":\"骞跨櫨瀹樻柟鍟嗗煄\",\"seller_nick\":\"骞跨櫨瀹樻柟鍟嗗煄\",\"buyer_nick\":\"lizhiqiang\",\"total_fee\":\"2000\",\"payment\":\"1800\",\"adjust_fee\":\"0\",\"discount_fee\":\"200\",\"point_fee\":\"0\",\"buyer_obtain_point_fee\":\"0\",\"post_fee\":\"100\",\"seller_memo	\":\"宸插\",\"buyer_message\":\"璇峰敖蹇畨鎺掔墿娴佸彂璐э紝璋㈣阿\",\"receiver_name\":\"鏉庡織寮篭",\"receiver_state\":\"婀栧寳鐪乗",\"receiver_city\":\"姝︽眽甯俓",\"receiver_district\":\"纭氬彛鍖篭",\"receiver_address\":\"姹夋锟�?90鍙穃",\"receiver_zip\":\"430033\",\"receiver_mobile\":\"13419644646\",\"receiver_phone\":\" \",\"invoice\":\"1\",\"invoice_name\":\"姝︽眽閲戝姏杞欢鏈夐檺鍏徃\",\"SysTemCon\":\"1\",\"SPLIST\":[{\"OrderItemId\":\"20131205000101\",\"sku_id\":\"123456789\",\"ProductID\":\"000001\",\" sp_title \":\"鏍煎姏2鍖圭┖璋僜",\"Price \":\"2000\",\"num\":\"1\",\"total_fee\":\"0\",\" adjust_fee_ITEM\":\"2000\",\"discount_fee_item\":\"200\",\"payment_item\":\"1800,\"WhNo \":\"01019901\" }]}";
		System.out.println(HttpClientUtils.httpGet(Url));*/
    }
}
